package main

import (
	"fmt"
	"gitee.com/libbylg/pkgr/repo"
	"os"
	"strings"
)

type CmdParseOptions struct {
	Label string
}

// NewCmdParseOptions 识别命令行选项.
// pkgr parse LABEL
func NewCmdParseOptions(argv []string) (*CmdParseOptions, error) {
	// 检查参数数量
	if len(argv) < 3 {
		return nil, fmt.Errorf("the required parameter is missing, try -h for help")
	}

	// 初始化默认值
	opt := &CmdParseOptions{
		Label: "",
	}

	pos := 0

	// 读取选项
	for index := 2; index < len(argv); index++ {
		// 遇到无法识别的选项
		if strings.HasPrefix(argv[index], "-") {
			return nil, fmt.Errorf("unsupported options `%v'", argv[index])
		}

		// 识别 Label 参数
		if pos == 0 {
			opt.Label = strings.TrimSpace(argv[index])
			pos++
			continue
		}

		return nil, fmt.Errorf("unsupported option `%v'", argv[index])
	}

	if opt.Label == "" {
		return nil, fmt.Errorf("missing the query label parameter, try -h for help")
	}

	return opt, nil
}

func CmdParse(argv []string) int {
	opt, err := NewCmdParseOptions(argv)
	if err != nil {
		ERROR("Load option for `%v' failed: %v", "query", err.Error())
		return 1
	}

	// 校验模块和版本号
	moduleLabel, err := repo.ParseModuleLabel(opt.Label)
	if err != nil {
		ERROR("Invalid module label `%v': %v", opt.Label, err.Error())
		return 1
	}

	fmt.Fprintf(os.Stdout, "MODULE_LABEL\t%v\n", moduleLabel.String())
	fmt.Fprintf(os.Stdout, "MODULE_NAME\t%v\n", moduleLabel.ModuleName)
	fmt.Fprintf(os.Stdout, "MODULE_VERSION\t%v\n", moduleLabel.ModuleVersion)

	for _, itemTrait := range moduleLabel.ModuleTraits {
		fmt.Fprintf(os.Stdout, "MODULE_TRAIT\t%v\t%v\n", itemTrait.Key, itemTrait.Val)
	}

	// 需要自动补齐的trait
	val, ok := moduleLabel.ModuleTraitsMapping[repo.BUILTIN_TRAIT_WAY]
	if !ok {
		fmt.Fprintf(os.Stdout, "MODULE_TRAIT\t%v\t%v\n", repo.BUILTIN_TRAIT_WAY, val)
	}

	return 0
}
